const {barrier} = require('./barrier.js');
const SerialPort = require('serialport');
const {SerIP,SerDev,videoDev} = require('./config.js');// 引入配置
const {parser} = require('./parser.js'); // 引入地磅解析函数
const request = require('request');

if(process.argv.length==2) {
    process.argv[2] = '--help';
}

const args = process.argv;

if(args[2] == '--help') {
    console.log('--help 输出帮助');
    console.log('--pound 3 1200/1600测试磅的波特率');
    console.log('--camera ip 车牌号,用于模拟推送车牌');
} else if(args[2] == '--pound') {
    if(args.length<5) {
        console.log('输入磅的编号和波特率');
    } else if(!/\d+/.test(args[3]) || !/\d+/.test(args[4]) ) {
        console.log('磅的编号和波特率应为数字');
    } else {
        let devNum = args[3];
        SerDev[devNum]['options']['baudRate'] = parseInt(args[4]); 
        let port = new SerialPort(SerDev[devNum]['dev'], SerDev[devNum]['options'],errback);
        port.on('readable', function () {
            let buff = port.read();
            console.log(buff,',',parser.decode(buff),'吨');
        });
    }
} else if(args[2] == '--camera') {
    if(args.length<5) {
        console.log('输入摄像头IP和摄像头的车牌号');
    } else {
        let url = 'https://'+SerIP+'/devicemanagement';
        request({
            url,
            method: "POST",
            json: true,
            strictSSL: false, // allow us to use our self-signed cert for testing
            headers: {
                "content-type": "application/json",
            },
            body: {
                    AlarmInfoPlate:{ipaddr:args[3],
                    result:{PlateResult:{license:args[4]}}}
                  }
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body,'连接正常') // 请求成功的处理逻辑
            } else {console.log(error)}
        });
    }
}

function errback(err) {
    if (err) {
      return console.log('Error: ', err.message)
    }
}